﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace sqlsearcher.Models
{
    public static class SystemDataHelper
    {
        public static List<T> ToList2<T>(this DataTable dt) where T : new()
        {
            List<T> ts = new List<T>();
            Type type = typeof(T);
            string tempName = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;

                    if (dt.Columns.Contains(tempName))
                    {
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];

                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }

                FieldInfo[] fields = t.GetType().GetFields();
                foreach (FieldInfo fi in fields)
                {
                    tempName = fi.Name;

                    if (dt.Columns.Contains(tempName))
                    {
                        object value = dr[tempName];

                        if (value != DBNull.Value)
                            fi.SetValue(t, value);
                    }
                }

                ts.Add(t);
            }
            return ts;
        }
    }
}
